package repository

import (
	"gorm.io/gorm"
	"guliedu/model"
)

type IEduCommentRepository interface {
	// 添加评论
	Insert(comment *model.EduComment) error
	// 查询对应课程的评论
	SelectByCourseID(courseID string, page, pageSize int) ([]model.EduComment, error)
	// 根据课程ID查询所有评论
	SelectAllByCourseID(courseID string) ([]model.EduComment, error)
	// 获取所有评论
	SelectAll(page, pageSize int) ([]model.EduComment, error)
	// 获取所有评论数
	SelectAllCount() (int64, error)
	// 删除评论
	Delete(id string) error
}

func NewIEduCommentRepository() IEduCommentRepository {
	return &EduCommentRepository{mysqlDb: db}
}

type EduCommentRepository struct {
	mysqlDb *gorm.DB
}

func (t *EduCommentRepository) SelectAllByCourseID(courseID string) (comments []model.EduComment, err error) {
	err = t.mysqlDb.Where("course_id = ?", courseID).Find(&comments).Error
	return
}

func (t *EduCommentRepository) Insert(comment *model.EduComment) error {
	return t.mysqlDb.Create(&comment).Error
}

func (t *EduCommentRepository) SelectAll(page, pageSize int) (comments []model.EduComment, err error) {
	err = t.mysqlDb.Offset((page - 1) * pageSize).Limit(pageSize).Find(&comments).Error
	return
}

func (t *EduCommentRepository) SelectByCourseID(courseID string, page, pageSize int) (comments []model.EduComment, err error) {
	err = t.mysqlDb.Where("course_id = ?", courseID).Offset((page - 1) * pageSize).Limit(pageSize).Find(&comments).Error
	return
}

func (t *EduCommentRepository) SelectAllCount() (count int64, err error) {
	err = t.mysqlDb.Model(&model.EduComment{}).Count(&count).Error
	return
}

func (t *EduCommentRepository) Delete(id string) error {
	return t.mysqlDb.Where("id = ?", id).Delete(&model.EduComment{}).Error
}
